package com.yugu.park.security;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.yugu.park.dto.Authorization;
import com.yugu.park.exception.BizException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author guxf
 * @date 2021/10/27
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {

    public static final ThreadLocal<Authorization> AUTHORIZATION = new ThreadLocal<>();
    private final String secret;

    public LoginHandlerInterceptor(String secret) {
        this.secret = secret;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String text = request.getHeader("token");
        if (StringUtils.isBlank(text)) {
            throw new BizException(401, "登录失败，认证信息错误");
        }
        Authorization authorization;
        try {
            authorization = Authorization.parseAuthorization(text, secret);
        } catch (Exception ex) {
            throw new BizException(401, "登录失败");
        }
        AUTHORIZATION.set(authorization);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        AUTHORIZATION.remove();
    }
}
